using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Authorization;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Shared.Enums;
using UniversalAdmin.Application.Commands;

namespace UniversalAdmin.Api.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class RequirePermissionAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
    {
        private readonly string _permissionCode;

        public RequirePermissionAttribute(string permissionCode)
        {
            _permissionCode = permissionCode;
        }

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // 检查用户是否已认证
            if (!context.HttpContext.User.Identity?.IsAuthenticated == true)
            {
                context.Result = new UnauthorizedObjectResult(new ApiResult
                {
                    Code = (int)ApiStatusCode.UNAUTHORIZED,
                    Message = "用户未登录，请先登录",
                    Data = null
                });
                return;
            }

            // 获取用户ID
            var userIdClaim = context.HttpContext.User.FindFirst("UserId");
            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                context.Result = new UnauthorizedObjectResult(new ApiResult
                {
                    Code = (int)ApiStatusCode.UNAUTHORIZED,
                    Message = "用户身份验证失败，请重新登录",
                    Data = null
                });
                return;
            }

            // 获取用户服务
            var userService = context.HttpContext.RequestServices.GetService<IAppUserServices>();
            if (userService == null)
            {
                context.Result = new StatusCodeResult(500);
                return;
            }

            // 检查用户是否有指定权限
            var hasPermission = await userService.HasPermissionAsync(userId, _permissionCode);
            if (!hasPermission)
            {
                // 获取用户当前权限，用于调试
                var userPermissions = await userService.GetUserPermissionsAsync(userId);
                
                context.Result = new ObjectResult(new ApiResult
                {
                    Code = (int)ApiStatusCode.FORBIDDEN,
                    Message = $"权限不足，需要 '{_permissionCode}' 权限才能执行此操作。当前用户权限：{string.Join(", ", userPermissions)}",
                    Data = new
                    {
                        RequiredPermission = _permissionCode,
                        CurrentPermissions = userPermissions,
                        Operation = context.HttpContext.Request.Method + " " + context.HttpContext.Request.Path
                    }
                })
                {
                    StatusCode = (int)ApiStatusCode.FORBIDDEN
                };
                return;
            }
        }
    }
} 